package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseList(head *ListNode) *ListNode {
	var prev, curr, next *ListNode
	curr = head
	for curr != nil {
		next = curr.Next
		curr.Next = prev
		prev = curr
		curr = next
	}
	return prev
}

func main() {
	// 将链表 1->2->3->4 反转
	node4 := ListNode{Val: 4, Next: nil}
	node3 := ListNode{Val: 3, Next: &node4}
	node2 := ListNode{Val: 2, Next: &node3}
	node1 := ListNode{Val: 1, Next: &node2}
	fmt.Println("原链表：")
	printList(&node1)
	fmt.Println("反转后的链表：")
	revList := reverseList(&node1)
	printList(revList)
}

// 打印链表元素
func printList(head *ListNode) {
	curr := head
	for curr != nil {
		fmt.Print(curr.Val, " ")
		curr = curr.Next
	}
	fmt.Println()
}
